<?php
/*
	本插件：$this->model('poster')->方法名();
	其他地方调用：model('jy_scrm/poster')->方法名();
*/
namespace jy_scrm;
defined('BY_JYA') or exit('error');
class poster extends \plugin{
	public function get_poster($type='game',$gameid='',$openid='')
	{
		$openid=$openid?:$_SESSION['openid'];
		$member=cfc('core')->member_show($_SESSION['uid']);
		if($type=='game'){
			$game=pdo_get('jy_scrm_sale_game',array('uniacid'=>$_SESSION['uniacid'],'id'=>$gameid));
			$userid=pdo_getcolumn('jy_scrm_worker',array('uniacid'=>$_SESSION['uniacid'],'id'=>$game['workerid']),'userid');
			$state='jy_scrm|mid|'.$_SESSION['uid'].'|game|'.$gameid;
			$workers=array();
			$workers[]=$userid;
			$post=array(
				'type'=>1,
				'scene'=>2,
				'remark'=>'活动海报',
				'skip_verify'=>true,
				'state'=>$state,
				'user'=>$workers,
			);
			$contact_way=$this->model('worker')->check_contact_way($state);
			if($contact_way){
				$post['config_id']=$contact_way['config_id'];
				$res=model('core/wxwork_userapi')->add_contact_way($post);
				$qr=$contact_way['qr_code'];
			}else{
				$res=model('core/wxwork_userapi')->add_contact_way($post);
				pdo_update('jy_scrm_sale_game',array('config_id'=>$res['config_id']),array('id'=>$gameid,'uniacid'=>$_SESSION['uniacid']));
				$this->model('worker')->add_contact_way($res);
				$qr=$res['qr_code'];
			}
			$poster=json_decode($game['poster_data'],true);
			$poster['id']='game'.$gameid;
			$poster['bg']=$poster['image'];
			$img=$this->createPoster($poster,$qr,$member,$gameid);
		}
		return tomedia($img);
	}
	public function createImage($imgurl) //从字符串中的图像流新建一图像
	{		
		$resp = cfc('http')->ihttp_request($imgurl);
		if (($resp['code'] == 200) && !(empty($resp['content']))) 
		{
			return imagecreatefromstring($resp['content']);
		}
		$i = 0;
		while ($i < 3) 
		{
			$resp = cfc('http')->ihttp_request($imgurl);
			if (($resp['code'] == 200) && !(empty($resp['content']))) 
			{
				return imagecreatefromstring($resp['content']);
			}
			++$i;
		}
		return '';
	}
	public function mergeImage($target, $data, $imgurl) 
	{
		$img = $this->createImage($imgurl);
		$w = imagesx($img);
		$h = imagesy($img);
		imagecopyresized($target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
		imagedestroy($img);
		return $target;
	}
	public function mergeText($target, $pos, $text,$addtext='') 
	{
		$font_file = ROOT_D . '/addons/jy_scrm/resource/msyh.ttf';
		$colors = $this->hex2rgb($pos['color']);
		$color = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
		if(!$pos['size']){
			$pos['size']='13px';
		}
		$pos['width']=$pos['width']?:280;
		$string=$text;
		$_string='';
		$__string='';
		for($i=0;$i<mb_strlen($string);$i++){
			$box=imagettfbbox($pos['size'],0,$font_file,$_string);
			$_string_length=$box[2]-$box[0];
			$box=imagettfbbox($pos['size'],0,$font_file,mb_substr($string,$i,1));
			if( $_string_length+$box[2]-$box[0]<$pos['width']){
				$_string.=mb_substr($string,$i,1);
			}else{
				$__string.=$_string."\n";
				$_string=mb_substr($string,$i,1);
			}
		}
		$__string.=$_string;
		$box=imagettfbbox($pos['size'],0,$font_file,mb_substr($__string,0,1));
		if($addtext){
			imagettftext($target, 20, 0, $pos['left'], $pos['top']+($box[3]-$box[7]), $color, $font_file, $addtext);
			$pos['left'] +=28;
		}
		imagettftext($target, $pos['size'], 0, $pos['left'], $pos['top']+($box[3]-$box[7]), $color, $font_file, $__string);
		//加粗
		if($pos['bold']==1){
			$pos['left'] +=1;
			imagettftext($target, $pos['size'], 0, $pos['left'], $pos['top']+($box[3]-$box[7]), $color, $font_file, $__string);
		}
		return $target;
	}
	public function hex2rgb($colour) 
	{
		if ($colour[0] == '#') 
		{
			$colour = substr($colour, 1);
		}
		if (strlen($colour) == 6) 
		{
			list($r, $g, $b) = array($colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5]);
		}
		else if (strlen($colour) == 3) 
		{
			list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
		}
		else 
		{
			return false;
		}
		$r = hexdec($r);
		$g = hexdec($g);
		$b = hexdec($b);
		return array('red' => $r, 'green' => $g, 'blue' => $b);
	}
	public function resizejpg($imgsrc,$path,$file2,$imgWidth,$imgHeight,$posterid){
		global $_AR;
		$arr = getimagesize($imgsrc); //获取图片信息宽、高 
		$imgsrc=$this->createImage($imgsrc);//转为图片流
		//$imgsrc = imagecreatefromstring($imgsrc);
		$image = imagecreatetruecolor($imgWidth, $imgHeight);  //创建一个彩色的底图
		imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]);
		imagepng($image, $path.$file2);
		imagedestroy($image);
		//要是网址形式
		if(($_SESSION['fromh5wxapp'] || $_SESSION['container']=='wxapp') && $_SESSION['wxapp_id']){
			$img = SITEROOT.RESOURCE . '/oss/'.$_SESSION['uniacid'].'/images/jy_scrm/wxapp' .$posterid.'/'. $file2;
		}else{
			$img = SITEROOT.RESOURCE . '/oss/'.$_SESSION['uniacid'].'/images/jy_scrm/' .$posterid.'/'. $file2;
		}
		return $img;
	}
	public function createPoster($poster, $qr, $updata,$gameid=0,$plugin='jy_scrm'){
		global $_AR;
		$poster['id']=$poster['id']?:'other';
		if(($_SESSION['fromh5wxapp'] || $_SESSION['container']=='wxapp') && $_SESSION['wxapp_id']){
			$path = ROOT_AT .'oss/'.$_SESSION['uniacid'].'/images/jy_scrm/wxapp'.$poster['id'].'/';
			$path2='oss/'.$_SESSION['uniacid'].'/images/jy_scrm/wxapp'.$poster['id'].'/';
		}else{
			$path = ROOT_AT .'oss/'.$_SESSION['uniacid'].'/images/jy_scrm/'.$poster['id'].'/';
			$path2='oss/'.$_SESSION['uniacid'].'/images/jy_scrm/'.$poster['id'].'/';
		}
		$copypath = ROOT_AT .'oss/'.$_SESSION['uniacid'].'/images/jy_scrm/';
		if (!(is_dir($path))) 
		{
			cfc('files')->mkdirs($path);
		}
		$data=$poster['data'];
		$md5 = $plugin.'poster'.$_SESSION['uid'].'id'.$poster['id'].'gameid'.$gameid;
		$file = $md5 . '.png';
		$file2 = $md5 . 'bg.png';
		$isadd=cfc('files')->source_check($path2.$file,'',true);
		if($isadd){
			if(($_SESSION['fromh5wxapp'] || $_SESSION['container']=='wxapp') && $_SESSION['wxapp_id']){
				$img = 'oss/'.$_SESSION['uniacid'].'/images/jy_scrm/wxapp' .$poster['id'].'/'. $file;
			}else{
				$img = 'oss/'.$_SESSION['uniacid'].'/images/jy_scrm/' .$poster['id'].'/'. $file;
			}
			return $img;	
		}
		if(!$isadd){
			set_time_limit(0);
			@ini_set('memory_limit', '256M');
			$target = imagecreatetruecolor(750, 996);//创建画布
			if($poster['bg']){
				$bg1 = tomedia($poster['bg']);
				$bgimg=$this->resizejpg($bg1,$path,$file2,750,996,$poster['id']);//生成背景图
				$bg = $this->createImage($bgimg);
				imagecopy($target, $bg, 0, 0, 0, 0, 750, 996);//将图片绘制在画布上
				imagedestroy($bg);//销毁背景图
			}else{
				$color = imagecolorallocate($target,255,255,255);//先分配一个白底
				imagefill($target,0,0,$color);//使用白色填充
			}
			foreach ($data as $d){
				$d = $this->getRealData($d);
				if ($d['type'] == 'head') {	
					$avatar =$updata['avatar'];
					$target = $this->mergeImage($target, $d, $avatar);
				}else if ($d['type'] == 'img') {
					$target = $this->mergeImage($target, $d, $d['src']);
				}else if ($d['type'] == 'qr') {	
					$target = $this->mergeImage($target, $d, tomedia($qr));
				}else if ($d['type'] == 'nickname'){
					$target = $this->mergeText($target, $d, $updata['nickname']);
				}else if ($d['type'] == 'text') {	
					$target = $this->mergeText($target, $d,$d['value']);
				}
			}
			imagepng($target, $copypath . $file);
			imagedestroy($target);
		}
		$img =  $copypath . $file;
		if(($_SESSION['fromh5wxapp'] || $_SESSION['container']=='wxapp') && $_SESSION['wxapp_id']){
			$filename='oss/'.$_SESSION['uniacid'].'/images/jy_scrm/wxapp'.$poster['id'].'/'.$file;
		}else{
			$filename='oss/'.$_SESSION['uniacid'].'/images/jy_scrm/'.$poster['id'].'/'.$file;
		}
		$title='海报'.$_SESSION['uniacid'].'_'.$poster['id'];
		$source=cfc('files')->source_save($img,'nochoose','png','',$filename);
		unlink($img);
		unlink($path . $file2);
		return $source;
	}
	public function getRealData($data) 
	{
		$data['left'] = intval(str_replace('px', '', $data['left'])) * 2;
		$data['top'] = intval(str_replace('px', '', $data['top'])) * 2;
		$data['width'] = intval(str_replace('px', '', $data['width'])) * 2;
		$data['height'] = intval(str_replace('px', '', $data['height'])) * 2;
		$data['size'] = intval(str_replace('px', '', $data['size'])) * 2;
		$data['src'] = tomedia($data['src']);
		return $data;
	}
	public function getitemData($data) 
	{
		$data['left'] = intval(str_replace('px', '', $data['left']));
		$data['top'] = intval(str_replace('px', '', $data['top']));
		$data['width'] = intval(str_replace('px', '', $data['width']));
		$data['height'] = intval(str_replace('px', '', $data['height']));
		$data['size'] = intval(str_replace('px', '', $data['size']));
		$data['src'] = tomedia($data['src']);
		return $data;
	}
	public function get_subscribeqr($item) 
	{
		$data=array(
			'title'=>trim($item['title']),
			'linkurl'=>'',
			'qrtype'=>2,
			'type'=>2,
			'eventtype'=>1,
			'plugin'=>'jy_scrm',
			'backid'=>'',
		);
		//微信二维码
		$getqrdata=array(
			'scantype'=>'follow',
			'id'=>$item['id'],
			'fromuser'=>$_SESSION['uid'],
		);
		$getqrdata = ijson_encode($getqrdata);
		$keyid='follow'.$item['id'].'mid'.$_SESSION['uid'];
		$res=model('core/account')->get_qr($data['type'],$data['plugin'],$getqrdata,$data['title'],'',$keyid);
		if(!$res['id']){
				exi('创建微信二维码失败！请检测微信公众号参数','error');
		}else{
				$update=array(
					'qrtype'=>$data['qrtype'],
					'eventtype'=>$data['eventtype'],
					'backid'=>'',
				);
				pdo_update('core_qr',$update,array('id'=>$res['id']));
		}
		return $res['file'];
	}
	public function get_fee($id,$fromuser=0) 
	{
		$poster=pdo_get('jy_scrm_poster',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		if($poster['reccredit'] && $fromuser){
			$tag='reccredit'.$id.'_'.$_SESSION['uid'];
			$isreccredit=pdo_getcolumn('core_credit_log',array('mid'=>$fromuser,'tag'=>$tag,'plugin'=>'jy_scrm','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$isreccredit){
				model('core/member')->member_credit($fromuser,'credit1',$poster['reccredit'],true,'jy_scrm','推荐人海报扫码',$tag);
			}
		}
		if($poster['recmoney'] && $fromuser){
			$tag='recmoney'.$id.'_'.$_SESSION['uid'];
			$recmoney=pdo_getcolumn('core_credit_log',array('mid'=>$fromuser,'tag'=>$tag,'plugin'=>'jy_scrm','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$recmoney){
				model('core/member')->member_credit($fromuser,'credit2',$poster['recmoney'],true,'jy_scrm','推荐人海报扫码',$tag);
			}
		}
		if($poster['subcredit'] && $_SESSION['uid']){
			$tag='subcredit'.$id;
			$subcredit=pdo_getcolumn('core_credit_log',array('mid'=>$_SESSION['uid'],'tag'=>$tag,'plugin'=>'jy_scrm','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$subcredit){
				model('core/member')->member_credit($_SESSION['uid'],'credit1',$poster['subcredit'],true,'jy_scrm','关注人海报扫码关注',$tag);
			}
		}
		if($poster['submoney'] && $_SESSION['uid']){
			$tag='submoney'.$id;
			$submoney=pdo_getcolumn('core_credit_log',array('mid'=>$_SESSION['uid'],'tag'=>$tag,'plugin'=>'jy_scrm','uniacid'=>$_SESSION['uniacid']),'id');
			if(!$submoney){
				model('core/member')->member_credit($_SESSION['uid'],'credit2',$poster['submoney'],true,'jy_scrm','关注人海报扫码关注',$tag);
			}
		}
		return true;
	}
}
?>